package dao;

import entity.Student;
import jdk.nashorn.internal.ir.CallNode;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import untils.DruidUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author:SA
 * @DATA:DATA
 * 学生数据持久化层的操作 写具体的实现方法
 */


public class StudentDaoImpl implements StudentDao{

    //添加学生
    @Override
    public int insertStudent(String id,String sname) {

        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "insert into student(id,sname)values(?,?)";
        try {
            int update = queryRunner.update(sql, id, sname);
            return  update;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return 0;
    }

    @Override
    public int delStudent(String id) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "delete from student where id = ?";
        try {
            int i = queryRunner.update(sql, id);
            return i;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateStudent(int stuNo, long clazzid) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "update student set classid = ? where id = ?";
        try {
            int line = queryRunner.update(sql, clazzid, stuNo);
            return line;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Student> selectAll() {

        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql="select student.id ,student.sname,student.classid,class.classname from student left join class on student.classid = class.id";

        try {
            List<Student> students = queryRunner.query(sql, new BeanListHandler<>(Student.class));
            return students;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public Student selectByName(String sname) {

        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "select id,sname,classid from student where sname = ?";
        try {
            Student student = queryRunner.query(sql, new BeanHandler<>(Student.class),sname);
            return student;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
